import requests
import pickle
import json
import os
from utils.log_output import simple_text_log


class StatusManager:
    def __init__(self):
        self.conf_path = os.path.join('config', 'conf.json')

    @property
    def es_ip(self):
        hyper_params = json.load(open(os.path.join('config', 'conf.json'), 'rt'))
        return hyper_params['es_ip']

    def gpu_status(self):
        url = f'{self.es_ip}/logs-train/_search'
        payload = {
            "from": 0,
            "size": 1,
            "query": {
                "match_all": { }
            },
            "fields": [
                "@timestamp",
                "content.msg"
            ],
            "_source": False,
            "sort": [
                {
                "@timestamp": "desc"
                }
            ]
        }

        try:
            r = json.loads(requests.post(url, json=payload).text)
            if 'hits' not in r or len(r['hits']['hits']) == 0:
                return 'GPU state not available.'
            else:
                msg = r['hits']['hits'][0]['fields']['content.msg'][0]
                ts = r['hits']['hits'][0]['fields']['@timestamp'][0]

                return f'({ts}) {msg}'
        except Exception as err:
            simple_text_log('error', str(err))


    def error_status(self):
        url = f'{self.es_ip}/logs-error/_search'
        payload = {
            "from": 0,
            "size": 1,
            "query": {
                "match_all": { }
            },
            "fields": [
                "@timestamp",
                "content.msg"
            ],
            "_source": False,
            "sort": [
                {
                "@timestamp": "desc"
                }
            ]
        }

        try:
            r = json.loads(requests.post(url, json=payload).text)
            if 'hits' not in r or len(r['hits']['hits']) == 0:
                return 'Error state not available.'
            else:
                msg = r['hits']['hits'][0]['fields']['content.msg'][0]
                ts = r['hits']['hits'][0]['fields']['@timestamp'][0]

                return f'({ts}) {msg}'
        except Exception as err:
            simple_text_log('error', str(err))
